<?php

namespace App\Http\Controllers\Admin\System;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Models\System\Menus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class MenusController extends AdminController
{

    public function data()
    {
        return $this->succeed([
            'rows' => Menus::query()->select(['id', 'name', 'display_name', 'url', 'icon', 'genre', 'parent_id', 'status', 'created_at'])->get(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:20|unique:system_menus',
            'display_name' => 'required'
        ], [
            'name.max' => '名称最大长度20个字符',
            'name.unique' => '名称已存在',
        ]);
        $data = $request->only(['parent_id', 'name', 'display_name', 'genre', 'icon', 'url', 'status']);
        try {
            DB::transaction(function () use ($data) {
                $model = Menus::query()->create([
                    'parent_id' => (int)$data["parent_id"],
                    'name' => $data["name"],
                    'display_name' => $data["display_name"],
                    'genre' => (int)$data['genre'] ?: 1,
                    'icon' => $data["icon"],
                    'url' => $data["url"],
                    'status' => (int)$data["status"]
                ]);
                Permission::query()->create(["guard_name" => static::GUARD_NAME, "name" => $data["name"]]);
                $this->createSyslog('添加菜单权限', $model);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function edit($id)
    {
        return $this->succeed(Menus::query()->findOrFail($id));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|max:20|unique:system_menus,name,'.$id.',id',
            'display_name' => 'required'
        ], [
            'name.max' => '名称最大长度20个字符',
            'name.unique' => '名称已存在',
        ]);
        $item = Menus::query()->findOrFail($id);
        $data = $request->only(['parent_id', 'name', 'display_name', 'genre', 'icon', 'url', 'status']);
        try {
            DB::transaction(function () use ($item, $data) {
                $oldName = $item['name'];
                $item->update([
                    'parent_id' => (int)$data["parent_id"],
                    'name' => trim($data["name"]),
                    'display_name' => trim($data["display_name"]),
                    'genre' => (int)$data['genre'] ?: 1,
                    'icon' => trim($data["icon"]),
                    'url' => trim($data["url"]),
                    'status' => (int)$data["status"]
                ]);
                if ($oldName !== $data['name']) {
                    Permission::query()->updateOrCreate(
                        ["name" => $oldName],
                        ["guard_name" => 'admin', "name" => $data['name']]
                    );
                }
                $this->createSyslog('更新菜单权限', $item);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        $list = Menus::query()->select(['id', 'name'])->whereIn('id', $ids)->withCount('children')->limit(static::QUERY_LIMIT)->get();
        abort_if($list->isEmpty(), ResponseEnum::DELETE_NOT_EXIST_ERROR);
        try {
            DB::transaction(function () use ($list) {
                foreach ($list as $model) {
                    abort_if($model->children_count > 0, ResponseEnum::PERMISSION_EXISTS_DELETE_ERROR);
                    $model->delete();
                    Permission::query()->where('name', $model->name)->where('guard_name', static::GUARD_NAME)->delete();
                    $this->createSyslog('删除菜单权限', $model);
                }
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }
}
